package com.cqvip.innocence.framework.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqvip.innocence.common.exception.ServiceException;
import com.cqvip.innocence.framework.jwt.dto.LoginAdmin;
import com.cqvip.innocence.project.model.entity.Admin;
import com.cqvip.innocence.project.model.entity.Resource;
import com.cqvip.innocence.project.model.entity.Role;
import com.cqvip.innocence.project.service.AdminService;
import com.cqvip.innocence.project.service.ResourceService;
import com.cqvip.innocence.project.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.cqvip.innocence.common.constant.JwtConstant.EXPIRE_TIME;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Admin> eq = new LambdaQueryWrapper<Admin>().eq(Admin::getName, username);
        Admin one = adminService.getOne(eq);
        if (null == one) {
            throw new ServiceException("登录用户：" + username + " 不存在");
        } else if (one.getLocked()) {
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        return createLoginAdmin(one);
    }

    public UserDetails createLoginAdmin(Admin admin) {
        LoginAdmin loginAdmin = new LoginAdmin();
        loginAdmin.setAdminUser(admin);
        loginAdmin.setExpireTime(EXPIRE_TIME * 30 * 1000L);
        loginAdmin.setLoginTime(System.currentTimeMillis());
        loginAdmin.setUserId(admin.getId().toString());
        loginAdmin.setUserName(admin.getName());
        loginAdmin.setPermissions(getAuthorities(admin));
        return loginAdmin;
    }

    protected Set<String> getAuthorities(Admin admin) {
        List<Role> roles = roleService.getRolesByAdmin(admin);
        HashSet<String> authorities = new HashSet<>();
        if (roles.isEmpty()) return null;
        for (Role role : roles) {
            authorities.add(role.getName());
            List<Resource> resourcesByRoleId = resourceService.getResourcesByRoleId(role);
            for (Resource resource : resourcesByRoleId) {
                authorities.add(resource.getPermission());
            }
        }
        return authorities;
    }
}
